package com.example.distortionmeter.viewmodel

import android.Manifest
import android.annotation.SuppressLint
import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.content.pm.PackageManager
import android.icu.text.SimpleDateFormat
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.runtime.mutableStateOf
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlin.math.sin

import com.example.distortionmeter.domain.BluetoothManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.Date
import java.util.Locale


class DistortionViewModel : ViewModel() {
    // ========================== 设备参数相关状态 ==========================
    private val _distortion = MutableStateFlow(0f)
    val distortion: StateFlow<Float> = _distortion

    private val _signalFrequency = MutableStateFlow(0f)
    val signalFrequency: StateFlow<Float> = _signalFrequency

    private val _gain = MutableStateFlow(0f)
    val gain: StateFlow<Float> = _gain

    private val _samplingRate = MutableStateFlow(0f)
    val samplingRate: StateFlow<Float> = _samplingRate

    // 波形数据
    private val _waveData = MutableStateFlow(List(24) { 0f })
    val waveData: StateFlow<List<Float>> = _waveData

    // 添加谐波数据状态
    private val _harmonicData = MutableStateFlow(List(10) { 0f })
    val harmonicData: StateFlow<List<Float>> = _harmonicData

    // ========================== 测量控制相关 ==========================
    private val _isMeasuring = MutableStateFlow(false)
    val isMeasuring: StateFlow<Boolean> = _isMeasuring.asStateFlow()
    private var measurementJob: Job? = null

    // ========================== 蓝牙相关状态 ==========================
    private val _bluetoothDevices = MutableStateFlow<List<BluetoothDevice>>(emptyList())
    val bluetoothDevices: StateFlow<List<BluetoothDevice>> = _bluetoothDevices

    private val _isScanning = MutableStateFlow(false)
    val isScanning: StateFlow<Boolean> = _isScanning

    private val _isConnected = MutableStateFlow<BluetoothDevice?>(null)
    val isConnected: StateFlow<BluetoothDevice?> = _isConnected

    private val _connectionState = MutableStateFlow(BluetoothManager.STATE_DISCONNECTED)
    val connectionState: StateFlow<Int> = _connectionState

    // 改用 SharedFlow 和缓冲队列
    private val _bluetoothErrors = MutableSharedFlow<String>(
        extraBufferCapacity = 10 // 根据需求调整缓冲区大小
    )
    val bluetoothErrors = _bluetoothErrors.asSharedFlow()

    // 权限回调接口
    private var permissionRequestCallback: ((perms: Array<String>, requestCode: Int) -> Unit)? = null

    // 蓝牙管理器实例
    private lateinit var bluetoothManager: BluetoothManager

    // 新增权限请求回调设置方法
    fun setPermissionCallback(callback: (perms: Array<String>, requestCode: Int) -> Unit) {
        this.permissionRequestCallback = callback
    }

    // 对话框显示状态
    private val _isDialogOpen = MutableStateFlow(false) // 使用 MutableStateFlow
    val isDialogOpen: StateFlow<Boolean> = _isDialogOpen.asStateFlow()




    fun setDialogState(isOpen: Boolean) {
        _isDialogOpen.value = isOpen
    }


    // ========================== 工具函数 ==========================
    // 更新传感器数据
    fun updateSensorData(
        thd: Float,
        freq: Float,
        rate: Float,
        gain: Float,
        wave: List<Float>,      // 前24个是波形数据
        harmonics: List<Float>  // 后10个是谐波成分
    ) {
        _distortion.value = thd
        _signalFrequency.value = freq
        _samplingRate.value = rate
        // 增益映射分支
        _gain.value = when (gain) {
            0f -> 3f          // 增益0 → 3.0
            1f -> 6.5f        // 增益1 → 6.5
            2f -> 13.5f       // 增益2 → 13.5
            3f -> 29.25f      // 增益3 → 29.25
            else -> gain      // 其他值保持原样（或根据需求设置默认值）
        }
        // 对每个波形数据减去 2047.5
        _waveData.value = wave.map { it - 2047.5f }
        // 对每个谐波数据乘以100(传入的是小数)
        _harmonicData.value = harmonics.map { it * 100 }
    }


    // ======================== 测量控制 =========================
    fun startMeasurement() {
        if (measurementJob?.isActive == true) return
        _isMeasuring.value = true
        measurementJob = viewModelScope.launch {
            while (_isMeasuring.value) {
                // 实际数据由蓝牙回调自动更新
                delay(1000)
            }
        }
    }

    fun stopMeasurement() {
        measurementJob?.cancel()
        measurementJob = null
        _isMeasuring.value = false
    }

    // ======================== 蓝牙管理 =========================
    fun initBluetoothManager(context: Context) {
        bluetoothManager = BluetoothManager(context).apply {
            setCallback(object : BluetoothManager.BluetoothCallback {
                override fun onDeviceFound(device: BluetoothDevice) {
                    // 更新设备列表（去重处理）
                    _bluetoothDevices.update { current ->
                        val exists = current.any { it.address == device.address }
                        if (exists) return@update current
                        ArrayList(current).apply { add(device) } // 使用更高效的更新方式
                    }
                }

                override fun onConnectionStateChanged(device: BluetoothDevice, state: Int) {
                    _connectionState.value = state
                    _isConnected.value = when (state) {
                        BluetoothManager.STATE_CONNECTED -> device
                        else -> null
                    }
                }

                override fun onDataReceived(thd: Float, freq: Float, rate: Float, gain: Float, data: List<Float>) {
                    if (_isMeasuring.value) { // 仅在测量时更新数据
                        if (data.size < 34) return

                        val wave = data.subList(0, 24)
                        val harmonics = data.subList(24, 34)

                        if (_isMeasuring.value) {
                            updateSensorData(thd, freq, rate, gain, wave, harmonics)
                        }
                    }
                }

                override fun onError(errorMessage: String) {
                    viewModelScope.launch {
                        _bluetoothErrors.emit(errorMessage)
                    }
                }
            })
        }
    }

    // 防抖时间戳
    private var _lastScanTimestamp =  MutableStateFlow(0L)
    val lastScanTimestamp: StateFlow<Long> = _lastScanTimestamp.asStateFlow() // 公开只读状态
    private val _lastScanTime = MutableStateFlow("")
    val lastScanTime: StateFlow<String> = _lastScanTime.asStateFlow()
    fun startScan() {
        viewModelScope.launch(Dispatchers.IO) { // 切换到IO线程
            val SCAN_COOLDOWN = 15000L // 调整为15秒
            val currentTime = System.currentTimeMillis()
            // 防抖检查
            if (currentTime - _lastScanTimestamp.value < SCAN_COOLDOWN) {
                val remaining = (SCAN_COOLDOWN - (currentTime - _lastScanTimestamp.value)) / 1000
                _bluetoothErrors.tryEmit("请等待${remaining}秒后重试")
                return@launch
            }

            // 第二步：统一权限检查（扫描需要SCAN权限）
            if (!checkAndRequestPermissions(isConnect = false)) return@launch

            // 更新扫描时间显示和状态
            _lastScanTimestamp.value = currentTime
            val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
            _lastScanTime.value = sdf.format(Date())
            _isScanning.value = true

            _bluetoothDevices.value = emptyList()// 清空设备列表
            withContext(Dispatchers.Main) { // UI更新切回主线程
                _bluetoothDevices.value = emptyList()
                _lastScanTime.value = sdf.format(Date())
            }

            // 启动扫描
            bluetoothManager.startDiscovery()
            launch {
                delay(10_000)
                stopScan()
                _isScanning.value = false
            }
        }
    }

    fun stopScan() {
        bluetoothManager.cancelDiscovery()
        _isScanning.value = false
    }

    fun connectToDevice(device: BluetoothDevice) {
        viewModelScope.launch {
            if (!checkAndRequestPermissions(isConnect = false)) return@launch

            // 先断开已有连接
            if (_isConnected.value != null) {
                bluetoothManager.closeConnection()
            }

            bluetoothManager.connectToDevice(device)
        }
    }

    fun disconnectDevice() {
        viewModelScope.launch {
            viewModelScope.launch {
                bluetoothManager.closeConnection(isManual = true) // 标记为主动断开
                _isConnected.value = null
            }
        }
    }


    // ======================== 权限管理 =========================
    private suspend fun checkAndRequestPermissions(isConnect: Boolean): Boolean {
        val perms = getRequiredPermissions(isConnect).toMutableList()

        // 新增定位权限检查（Android 12及以上蓝牙扫描需要）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !perms.contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
            perms += Manifest.permission.ACCESS_FINE_LOCATION
        }

        // 后续权限检查逻辑保持不变
        val granted = perms.all {
            ContextCompat.checkSelfPermission(bluetoothManager.context, it) == PackageManager.PERMISSION_GRANTED
        }

        if (!granted) {
            withContext(Dispatchers.Main) {
                permissionRequestCallback?.invoke(perms.toTypedArray(), BluetoothManager.REQUEST_BLUETOOTH)
            }
            return false
        }
        return true
    }

    private fun getRequiredPermissions(isConnect: Boolean = false): Array<String> {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (isConnect) arrayOf(Manifest.permission.BLUETOOTH_CONNECT)
            else arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT
            )
        } else {
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
        }
    }


    // ======================== 生命周期 =========================
    override fun onCleared() {
        super.onCleared()
        bluetoothManager.release()
        stopMeasurement()
    }
}

